package com.me.web;

import com.me.dao.IVetDao;
import com.me.dao.impl.VetDao;
import com.me.dao.impl.VisitDao;
import com.me.domain.Vet;
import com.me.domain.Visit;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/Visit")
public class VisitServlet extends BaseServlet {
    @Override
    protected void doGet() throws ServletException, IOException {
        String m = getParam("m");
        if ("showHistory".equals(m)){
            showHistory();
        }else if("toAdd".equals(m)){
                toAdd();
        }else if ("del".equals(m)){
            del();
        }
    }

    private void del() throws ServletException, IOException {
        VisitDao visitDao = new VisitDao();
        int id = getIntParam("id");
        int petid = getIntParam("petid");
        visitDao.del(id);
        forward("/petmanage?m=detail&id=" + petid);
    }

    private void toAdd() throws ServletException, IOException {
        try {
            VetDao vetDao = new VetDao();
            List<Vet> vets = vetDao.getAll();
            setReqAttr("vets",vets);
            forward("/admin/petVisitAdd.jsp");
        }catch (Exception e){
            setReqAttr("msg",e.getMessage());
            showHistory();
        }
    }

    @Override
    protected void doPost() throws ServletException, IOException {
        try {
            IVetDao vdao = new VetDao();
            Visit visit = new Visit();
            visit.setPetId(getIntParam("petId"));
            String vetName = getParam("vet");
            visit.setVetId(vdao.getByName(vetName).getId());
            visit.setDescription(getParam("description"));
            visit.setTreatment(getParam("treatment"));
            VisitDao visitDao = new VisitDao();
            visitDao.save(visit);
            setReqAttr("msg","病历添加成功");
            forward("./petmanage?m=detail&id="+getParam("petId"));
        }catch (Exception e){
            setReqAttr("msg",e.getMessage());
            forward("/admin/petVisitAdd.jsp");
        }
    }
    private void showHistory() throws ServletException, IOException {
        try {
            VisitDao vistDao = new VisitDao();
            List<Visit> visits = vistDao.getVisitsByPetId(Integer.parseInt(getParam("petId")));
            setReqAttr("visits", visits);
            if (visits.size() == 0) {
                setReqAttr("msg", "没有找到病历");
            }
            forward("/visitsearch_result.jsp");
        } catch (Exception e) {
            setReqAttr("msg",e.getMessage());
            forward("/customersearch.jsp");
        }
    }
}
